﻿#include "ChannelView.h"
#include "Log.h"
#include <qevent.h>
#include "Note.h"

constexpr int chan_item_width{ 150 }, chan_item_height{ 100 };

ChannelView::ChannelView(QWidget* parent) :
	QGraphicsView{ parent },
	posAnchor{},
	centerAnchor{},
	mouse_button{},
	max_z_value{},
	sens{},
	channels{},
	current_item{},
	current_col{},
	current_row{},
	pitch_count{ 5 }
{
	this->setScene(&sens);
}

ChannelView::~ChannelView()
{

}

ChannelWidget* ChannelView::emplase_channel(const ChannelCreateInfo* i)
{
	auto temp_channel = new ChannelWidget(i);
	connect(temp_channel, &ChannelWidget::sig_closed, this, &ChannelView::slot_remove_channel);
	auto gitem = this->sens.addWidget(temp_channel);

	auto x = channels.size() % pitch_count;
	auto y = channels.size() / pitch_count;

	temp_channel->move(x * chan_item_width, y * chan_item_height);

	channels.push_back({ temp_channel,gitem });
	return temp_channel;
}

void ChannelView::mousePressEvent(QMouseEvent* event)
{
	QGraphicsView::mousePressEvent(event);
	this->mouse_button = event->button();
	posAnchor = event->pos();
	centerAnchor = mapToScene(posAnchor) - posAnchor + QPointF(width() / 2, height() / 2);

	this->current_item = scene()->itemAt(mapToScene(event->pos()), transform());

	if(this->current_item != nullptr && this->mouse_button == Qt::LeftButton)
	{
		this->current_item->setZValue(++max_z_value);
	}
}

void ChannelView::mouseMoveEvent(QMouseEvent* event)
{
	QGraphicsView::mouseMoveEvent(event);
	/*Logger().info("view move");*/
	//Move Scene
	if(this->mouse_button == Qt::RightButton)
	{
		QPointF offsetPos = event->pos() - posAnchor;
		setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
		centerOn(centerAnchor - offsetPos);
	}
	////Move item
	//if(this->mouse_button == Qt::LeftButton)
	//{
	//	auto p = event->position();
	//	Logger().info("Mouse Pos : {},{}", p.x(), p.y());
	//}
}

void ChannelView::resizeEvent(QResizeEvent* event)
{
	Logger().info("last size {},{}", event->size().width(), event->size().height());
	this->pitch_count = event->size().width() / chan_item_width;
	QGraphicsView::resizeEvent(event);
}

void ChannelView::slot_reset_layout()
{
	for(size_t i = 0; i < channels.size(); i++)
	{
		auto& chan = channels[i];
		auto x = i % pitch_count;
		auto y = i / pitch_count;

		chan.first->move(x * chan_item_width, y * chan_item_height);
	}
}

void ChannelView::mouseReleaseEvent(QMouseEvent* event)
{
	QGraphicsView::mouseReleaseEvent(event);
	if(event->button() == this->mouse_button)
	{
		this->mouse_button = Qt::NoButton;
	}
}

void ChannelView::slot_remove_channel(ChannelWidget* chan)
{
	Note note{ "确认删除通道？" };
	if(note.showDialog())
	{
		for(auto& item : channels)
		{
			if(item.first == chan)
			{
				this->sens.removeItem(item.second);
				item.first->deleteLater();
				item.second->deleteLater();
				item = channels.back();
				channels.pop_back();

				break;
			}
		}
	}
}